package com.zyy.joseata.interceptor;

import com.zyy.joseata.constant.TxConst;
import com.zyy.joseata.util.JoSeataContextUtil;
import com.zyy.joseata.util.ThreadLocalUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

/**
 * @author zhangyy
 */
@Configuration
@Slf4j
public class JoSeataFeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        String txId= JoSeataContextUtil.getAttrTxId();
        if(requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            //Object txId = request.getAttribute(TxConst.JOSEATA_TXID_HEADER);
            if(txId != null){
                Enumeration<String> headerNames = request.getHeaderNames();
                String key;
                while(headerNames.hasMoreElements()){
                    key = headerNames.nextElement();
                    requestTemplate.header(key,request.getHeader(key));
                }
                requestTemplate.header(TxConst.JOSEATA_TXID_HEADER,txId.toString());
            }
        }

    }
}
